#!/usr/bin/perl
use strict;
use modules::encode;
package nsregister;

sub nsregister {
    use Digest::MD5 qw(md5_base64);
    my ($nsnum,$dbh,$remote,$input) = @_;
    my $sth;
    my $auth;
#GET THE NINFO
    $sth=$dbh->prepare("SELECT num,nick,host,auth FROM ninfo WHERE num = '$$input[0]' AND code = '".encode::encode($$input[0])."';");
    $sth->execute;
    my $nick;my $host;
    while (my @tmp = $sth->fetchrow_array) {
	if ($tmp[0] eq $$input[0]) {
	    $nick = $tmp[1]; $host = $tmp[2]; $auth = $tmp[3];
	}
	undef @tmp;
    }
   
#CHECK IF ISREG
    $sth = $dbh->prepare("SELECT rnick FROM nicks WHERE rnick = '$nick';");
    $sth->execute;
    my $isreg = $sth->fetchrow_array;
#CHECK EMAIL
    if ($$input[4] eq "") {
	print $remote "$nsnum O $$input[0] :Syntax: REGISTER <email>\n";
    }
    elsif ($$input[4] =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/ || $$input[4] !~ /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z0-9]+)(\]?)$/) {
	print $remote "$nsnum O $$input[0] :Bad email.\n";
    }
    elsif ($isreg) {
	print $remote "$nsnum O $$input[0] :This nickname is already registered.\n";
    }
    elsif (length($$input[5]) > 50) {
	print $remote "$nsnum O $$input[0] :Email is too long.(strlen)\n";
    }
    elsif ($auth ne '0') {
	print $remote "$nsnum O $$input[0] :You are authenticated as $auth.\n";
    }
    else {
	my $time = time;
	my $passwd = md5_base64($time);     
    
	my $doublecrypt = md5_base64($passwd);
       
	$sth=$dbh->prepare("INSERT INTO nicks values ('$nick','$doublecrypt','$$input[4]',0,'$host','$time',0);");
	$sth->execute;
	print $remote "$nsnum O $$input[0] :Registration Successful!, please check your email for your password. If you do not change your password by 1 day, your nick will be unregistered..\n";
	open (MAIL,"|/usr/sbin/sendmail -t");
	print MAIL "To: $$input[4]\n";
	print MAIL "From: channelservices\@maxismedia.net\nSubject: Your registered nickname\n";
	print MAIL "Congratulations! you have registered your nickname $nick successfully.\n";
	print MAIL "Your password is $passwd \n";
	print MAIL "Don't forget to change it, else your nick will be unregistered.\n";
	print MAIL "Thank you for using CSWorld IRC Services, have a nice day.\n";
	close (MAIL);
	my $time = time;
	$sth=$dbh->prepare("INSERT INTO pendingnicks values ('$nick','$time');");
	$sth->execute;
    
    }

}


1;

